package cn.mxz.xmu.robots.library.basic;

import wang.mouge.common.util.cache.MemcachedClient;
import wang.mouge.crawler.core.CrawlerFactory;
import wang.mouge.dubbo.service.crawler.ICrawler;
import wang.mouge.dubbo.service.crawler.Request;
import cn.mxz.xmu.interfaces.dubbo.Debug;
import cn.mxz.xmu.restful.util.NoCrawlerException;
import cn.mxz.xmu.robots.basic.RobotsUtlis;

/**
 * 图书馆机器人
 * 
 * @author dongchao <dongchao@mouge.wang>
 * @since 2015-07-23
 */
public abstract class Library implements ILibrary, ILibraryStatus
{
	private ICrawler mCrawler;

	public Library()
	{
		mCrawler = CrawlerFactory.newInstance("HtmlUnit");
	}

	/**
	 * 根据参数的类型和参数，构造出一个Url
	 * 
	 * @param type
	 *            需要的Url的类型
	 * @param params
	 *            需要构造的Url的参数
	 * @return 构造好的Url
	 */
	protected abstract String buildUrl(String type, String params);

	/**
	 * 封装了底层爬虫的curlPost请求，能够过滤掉无效的返回结果
	 * 
	 * @param request
	 *            http请求信息
	 * @return 请求结果
	 */
	protected String curlPost(Request request)
	{
		request.setCrawlerId("mxz");
		request.setCrawlerType("HtmlUnit");
		request.setCrawlerMethod("curlPost");
		String result = null;

		if (!Debug.console_value)
			result = mCrawler.curlPost(request);

		if (result.contains("NO_CRAWLER"))
			throw new NoCrawlerException(result);

		return result;
	}

	/**
	 * 将字符串进行URLEncode加密
	 * 
	 * @param input
	 *            加密之前的字符串
	 * @return 加密之后的字符串
	 */
	protected String urlEncode(String input)
	{
		return RobotsUtlis.urlEncode(input);
	}

	/**
	 * 正则匹配
	 * 
	 * @param str
	 *            要匹配的字符串
	 * @param regex
	 *            匹配的规则
	 * @return 匹配成功的字符串
	 */
	public static String regexMatch(String str, String regex)
	{
		return RobotsUtlis.regexMatch(str, regex);
	}

	protected void setCache(String key, String value)
	{
		MemcachedClient.set(key, value);
	}

	protected String getCache(String key)
	{
		return MemcachedClient.get(key);
	}
}
